package com.kavian.test.image;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

/**
 * @Filename: MyTools→com.kavian.test.image→ImageLucency.java
 * @Description: 图片旋转
 * @Copyright: Copyright (c)2012
 * @Company: qoocc
 * @author: kavian
 * @version: 1.0 Create at: 2012-6-27下午8:04:15
 * 
 *           Modification History: Date Author Version Description
 *           ------------------------------------------------------------------
 *           2012-6-27下午8:04:15 Administrator 1.0 1.0 Version
 */
public class RevolveImage {

	/**
	 * @description 	图片旋转
	 * @param file 文件名
	 * @param degree 角度
	 * @throws Exception
	 * kavian  2012-6-27下午8:34:16	
	 */
	public static void rotateImage(final File file, final int degree)
			throws Exception {
		BufferedImage bufferedimage = ImageIO.read(file);
		String endName = file.getName();
		endName = endName.substring(endName.lastIndexOf(".") + 1);

		int w = bufferedimage.getWidth();
		int h = bufferedimage.getHeight();

		double rotation = 0;
		int _w = w;
		int _h = h;
		int _degree = degree;
		if (_degree >= 0) {
			rotation = Math.PI * _degree / 180;
		} else {
			rotation = Math.PI * (360 + _degree) / 180;
		}

		double costheta = Math.cos(rotation);
		double sintheta = Math.sin(rotation);

		w = (int) (Math.abs(costheta * _w + 0.5) + Math
				.abs(sintheta * _h + 0.5));
		h = (int) (Math.abs(costheta * _h + 0.5) + Math
				.abs(sintheta * _w + 0.5));

		int type = bufferedimage.getColorModel().getTransparency();
		BufferedImage img;
		Graphics2D graphics2d;
		(graphics2d = (img = new BufferedImage(w, h, type)).createGraphics())
				.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
						RenderingHints.VALUE_INTERPOLATION_BILINEAR);
		graphics2d.rotate(Math.toRadians(-degree), w / 2, h / 2);
		int x = (int) (w * 0.5 - _w * 0.5);
		int y = (int) (h * 0.5 - _h * 0.5);
		graphics2d.drawImage(bufferedimage, x, y, null);
		graphics2d.dispose();

		ImageIO.write(img, endName,file);
	}

	public static void main(String[] args) throws Exception {
		File file = new File("d://1.jpg");
		rotateImage(file,-15);
	}
}